<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of CContests
 *
 * @author andrea
 */
class CContests_vidwiz extends Controller_vidwiz{

    public function insertContest($title,$startDate,$stopDate,$description,$type,$winnerSelection,$ratingDuration,$uploadDuration){
        $check = USingleton_vidwiz::getInstances("UChecks_vidwiz");
        $model = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $entity = USingleton_vidwiz::getInstances("EContests_vidwiz");
        $error[] = $check->check_title($title);
        $error[] = $check->check_date($stopDate);
        $error[] = $check->check_date($startDate);
        $error[] = $check->check_description($description);
        
        if($ratingDuration != "")
            $error[] = $check->check_ratingDuration($ratingDuration);
        $error[] = $check->check_ratingDuration($uploadDuration);
        if($type === false || ($type != "open" && $type != "private"))
            $type="private";
        if($winnerSelection === false || ($winnerSelection != "1" && $winnerSelection != "0")){
            $winnerSelection = "1";
            $ratingDuration = "7";
            }
        if($winnerSelection == "0")
            $ratingDuration = "0";
        $stopDate = $model->dateToISO($stopDate);
        $startDate = $model->dateToISO($startDate);
        
        if(in_array(false, $error))
            die(__("C'e' stato un errore nel trasferimento dei dati",'vidwiz-plugin'));

        //inserire codice tale da aggiungere la pagina del contest.
        $post['post_title'] = "$title";
        $post['post_content'] = "";
        $post['post_status'] = 'draft';
        $post['post_type'] = 'contest';
        $post['comment_status'] = 'closed';
        $post['ping_status'] = 'closed';
        $pageId = wp_insert_post( $post );
        $contest = $entity->generateObject(array(
            "description"       => $description,
            "startDate"         => $startDate,
            "title"             => $title,
            "stopDate"          => $stopDate,
            "contestType"       => $type,
            "winnerSelection"   => $winnerSelection,
            "ratingDuration"    => $ratingDuration,
            "uploadDuration"    => $uploadDuration,
            "page_id"           => $pageId
        ));
        
        $query = $model->insertQuery($contest);
        $model->executeQuery($query);
        $this->checkContests();
    } // end of member function createPalinsesto
    
    /**
     * Controlla se ci sono contests attivi/finiti e modifica tali informazioni sul db
     * qualora fossero errate
     * @global array $config 
     */
    public function checkContests(){
        $model = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        
        $this->checkContestStart();
        $this->checkEndOfSubscriptions();
        $this->checkEndOfUserValidation();
        $this->checkEndOfVideoValidation();
        $this->checkCanVote();
        $this->closeContests();
        
    }

    public function checkContestStart(){
        $model = new MContests_vidwiz();//USingleton_vidwiz::getInstances("MContests_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        global $config;     $date = date("Y-m-d")." 00:00:00";
        $date = date("Y-m-d")." 00:00:00";
        $where = array(
            array('status','=','announced'),
            array('startDate',"<=",$date),
        );
        $valueSet = array(
            array("status","subscription")
        );
        $query = $model->updateQuery($config['tables']['contests'], $valueSet, $where);
        $model->executeQuery($query);
    }
    
    /**
     * Controlla se è terminata la fase di iscrizione degli utenti . In caso di risposta positiva,
     * Cambia lo stato del contest e imposta la data di stop alla data attuale.
     * Tale caratteristica viene utilizzate per determinare la data del fine upload.
     */
    public function checkEndOfSubscriptions(){
        //Se lo status è subscription e la data di iscrizione è stata superata
        //allora la fase di iscrizione degli utenti è terminata
        $model = new MContests_vidwiz();//USingleton_vidwiz::getInstances("MContests_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        global $config;     $date = date("Y-m-d")." 00:00:00";
        $where = array(
            array('status','=','subscription'),
            array('stopDate',"<=",$date),
        );
        $valueSet = array(
            array("status","user_validation")
        );
        
        $query = $model->updateQuery($config['tables']['contests'], $valueSet, $where);
        $model->executeQuery($query);
    }
    
    /**
     * Controlla se è terminata la fase di validazione degli utenti (controllando che non ci 
     * siano altri utenti da validare). In caso di risposta positiva,
     * Cambia lo stato del contest e imposta la data di stop alla data attuale.
     * Tale caratteristica viene utilizzate per determinare la data del fine upload.
     */
    public function checkEndOfUserValidation(){
        //Se lo status è user_validation e non ci sono più utenti da validare
        //allora la fase di validazione degli utenti è terminata
        $MContests = new MContests_vidwiz();//USingleton_vidwiz::getInstances("MContests_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        global $config;
        $where = array(
            array("user_approved","=","0")
        );
        $contestsWithPendingUsers = $MContests->searchQuery($config['tables']['partecipations'], $where, array("contestid"), false, false, false, "GROUP BY contestid");
        $where = array(
            array("status","=","user_validation"),
            array("id"," NOT IN ","(".$contestsWithPendingUsers.")")
            );
        $valueSet = array(
            array("status","video_validation"),
            array("stopDate",date("Y-m-d h:i:s"))
            );
        /*
         * Nel momento in cui si aggiornano i contest, bisogna avvisare gli utenti
         * iscritti che la fase di validazione degli utenti è terminata. Percui
         * Potrà iniziare la fase di upload dei video.
         */
        $userValidationCouldBeEnded = $MContests->searchQuery($config['tables']['contests'], $where,array("id"));
        $IDs = $MContests->getRowsAssoc($userValidationCouldBeEnded);
        $query = $MContests->updateQuery($config['tables']['contests'],$valueSet,$where);
        $MContests->executeQuery($query);
        foreach ($IDs as $value)
            $this->sendMailsEndOfUserValidation($value['id']);
    }
    
    /**
     * Controlla se è terminata la fase di validazione dei video (controllando che non ci 
     * siano altri video da validare). In caso di risposta positiva,
     * Cambia lo stato del contest e imposta la data di stop alla data attuale.
     * Tale caratteristica viene utilizzate per determinare la data del fine delle votazioni.
     * @param $contestid int l'id del contest da controllare
     * @return false in caso la fase sia terminata, true altrimenti.
     */
    public function checkEndOfVideoValidation(){
        //la fase di valutazione video, termina se (è scaduta
        //la data entro la quale è possibile fare l'upload AND se non ci sono video
        //in via d'approvazione)
        $MContests = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $check = new UChecks_vidwiz();
        global $config;
        $where = array(
            array("status","=","video_validation")
            );
        $videoValidationCouldBeEnded = $MContests->searchQuery($config['tables']['contests'], $where,array("id"));
        /*
         * Prende gli id dei contest i quali hanno ancora utenti che non hanno uploadato
         * il video. Per questi bisogna infatti controllare che non siano scaduti
         * i termini di tempo per effettuare l'upload. In caso i termini per l'upload
         * siano scaduti, si imposta il videoid a -1
         */
        $IDs = $MContests->getRowsAssoc($videoValidationCouldBeEnded);
        foreach($IDs as $value){
                if(!$check->check_canUploadVideoInContest($value['id'])){
                    /*
                     * Imposta il videoid a -1 per gli utenti che hanno dimenticato di 
                     * effetture l'upload
                     */
                    $where = array(
                        array("contestid","=",$value['id']),
                        array("videoid","=","0")
                    );
                    $valueSet = array(
                        array("videoid","-1")
                        );
                    $query = $MContests->updateQuery($config['tables']['partecipations'],$valueSet,$where);
                    $MContests->executeQuery($query);
                    /*
                     * Terminal la fase di validazione del 
                     */
                    $where = array(
                        array("id","=",$value['id'])
                        );
                    $valueSet = array(
                        array("status","ending_validation")
                    );
                    $query = $MContests->updateQuery($config['tables']['contests'], $valueSet, $where);
                    
                    $MContests->executeQuery($query);
                    
            }
        }
    }

    public function checkCanVote(){
        $MContests = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        global $config;
        $where = array(
            array("status","=","ending_validation"),
            array("videoid","<>","-1"),
            array("video_approved","=","0")
        );
        $contestsWithPendingVideo = $MContests->searchQuery($config['tables']['partecipations'], $where, array("contestid"), false, false, false, "GROUP BY contestid");
        $where = array(
            array("status","=","ending_validation"),
            array("id"," NOT IN ","(".$contestsWithPendingVideo.")")
        );
        $valueSet = array(
            array("status","voting"),
            array("stopDate",date("Y-m-d h:i:s"))
            );
        $query = $MContests->searchQuery($config['tables']['contests'],$where);
        $results = $MContests->getRowsAssoc($query);
        $query = $MContests->updateQuery($config['tables']['contests'], $valueSet, $where);            
        $MContests->executeQuery($query);
        $debug->debugLog($results);
        foreach($results as $value){
            $this->sendMailsEndOfVideoValidation($value["id"]);
            if($value['winnerSelection'] == "1")
                $this->enableContestPageAccess($value['id']);
            }
        
    }
    
    public function closeContests(){
        $model = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $check = new UChecks_vidwiz();
        global $config;
        $where = array (
                array("placing","=","0"),
                array("user_approved","<>","-1"),
                array("video_approved","<>","-1"),
                array("videoid","<>","-1")
            );
        $noEndedContests = $model->searchQuery($config["tables"]['partecipations'],$where,array("contestid"),false,false,false," GROUP BY contestid");
        $where = array(
            array("status","=","voting"),
            array("id"," NOT IN","(".$noEndedContests.")"),
            array("winnerSelection","=","0")
        );
        /*
         * Imposta lo status a closed, di tutti quei contest che hanno tutte le posizioni
         * riempite (intese come posizione in classifica degli utenti iscritti)
         * e che richiedono la votazione diretta da parte degli admin. Tali contest
         * sono infatti sicuramente chiusi.
         */
        $query = $model->updateQuery($config['tables']['contests'], array(array("status","closed")), $where);
        
        $model->executeQuery($query);
        $where = array(
            array("status","=","voting"),
            array("id"," IN","(".$noEndedContests.")"),
            array("winnerSelection","=","1")
        );
        $couldBeClosed = $model->searchQuery($config["tables"]['contests'],$where,array("id"));
        /*
         * $couldBeClosed contiene i contest potenzialmente chiusi, ossia quelli
         * che sono da votare da parte degli utenti e che non sono già chiusi. Il ciclo li
         * esamina singolarmente e, in caso siano effettivamente chiusi 
         * imposta lo status a close
         */
        
        $couldBeClosed = $model->getRowsAssoc($couldBeClosed);
        foreach($couldBeClosed as $key => $value){
            $contestid = $value['id'];
            if(!$check->check_canVoteContest($contestid)){
                $where = array(array("id","=",$contestid));
                $query = $model->updateQuery($config['tables']['contests'], array(array("status","closed")),$where);
                
                $model->executeQuery($query);
            }
        }
        $query = $model->searchQuery($config['tables']['contests'], array(array("status","=","closed")), array("id"));
        /*
         * Reperisce tutti i contest che sono stati appena chiusi
         */
        $closedContests = $model->getRowsAssoc($query);
        /*
         * Per ogni contest chiuso, effettua le operazioni all'interno del ciclo
         */
        foreach($closedContests as $key => $value){
            $contestid = $value['id'];
            $contest = $model->getContestFromId($contestid);
            $contestname = $contest['title'];
            $charts = $this->makeCharts($contestid);
            $where = array(
                array("id","=",$contestid)
            );
            
            $query = $model->updateQuery($config['tables']['contests'], array(array("status","mail_sent")),$where);
            $model->executeQuery($query);
            $this->sendMailsCharts($charts,$contestname);
            }
    }

    public function getRating($videoId){
        $model = USingleton_vidwiz::getInstances("MScores_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        global $config;
        $where = array(
            array("videoid","=",$videoId)
        );
        $fieldAvg = "score";
        $rating = $model->avgQuery($config['tables']['scores'],$fieldAvg,$where);
        
        return $model->getRowsAssoc($rating);
    }
    
    public function makeCharts($contestid,$justGet = false){
        $MScore = USingleton_vidwiz::getInstances("MScores_vidwiz");
        $MContest = new MContests_vidwiz();
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $MContest = USingleton_vidwiz::getInstances("MContests_vidwiz");
        global $config;
        //classifica dall'ultima posizione alla prima
        $contest = $MContest->getContestFromId($contestid);
        $charts = $MScore->getCharts($contestid);
        //$charts = $this->fixCharts($charts);
        $count = count($charts);
        if($justGet == false)
            if($contest["winnerSelection"] == "1"){
                foreach($charts as $key => $value){
                    $valueSet = array(
                        array("placing",$count)
                    );
                    $where = array(
                        array("videoid","=",$value['videoid'])
                    );
                    $update = $MContest->updateQuery($config['tables']['partecipations'],$valueSet,$where);
                    $MContest->executeQuery($update);
                    $charts[$key]['position'] = $count;
                    $count--;
                }
            }
            else{
                foreach($charts as $key => $value){
                    $charts[$key]['position'] = $count;
                    $count--;
                }
            }        
        return $charts;
    }
    
    public function sendMailsCharts($charts,$contestname){
        $model = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $wordpress = USingleton_vidwiz::getInstances("UWordpress_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $umail = USingleton_vidwiz::getInstances("UMails_vidwiz");
        global $config;
        foreach($charts as $key => $value){
            $where = array(
                array("videoid","=",$value["videoid"])
            );
            $query = $model->searchQuery($config['tables']['partecipations'],$where,array("userid"));
            $results = $model->getRowsAssoc($query);
            $userid = $results[0]['userid'];
            $userdata = $model->getUserDataFromId($userid);
            $position = $value['position'];
            $umail->send_contestClosedAndCharts($userdata->user_email,$userdata->user_login,$contestname,$position);
        }
       
    }
    
    public function sendMailsEndOfUserValidation($contestid){
        $MContests = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $umail = USingleton_vidwiz::getInstances("UMails_vidwiz");
        global $config;
        $where = array(
            array("contestid","=",$contestid)
            );
        /*
         * Tutti i video per cui la validazione è sicuramente terminata
         */
        $userValidationEndedIDs = $MContests->searchQuery($config['tables']['contests'], $where, array("id"));
        $from = array(
            $config['tables']['partecipations'],
            $config['tables']['users'],
            $config['tables']['contests']
            );
        $join = array(
            array($config['tables']['partecipations'].".userid",$config['tables']['users'].".ID"),
            array($config['tables']['partecipations'].".contestid",$config['tables']['contests'].".id")
        );
        $where = array(
            array($config['tables']['partecipations'].".contestid"," IN ","(".$userValidationEndedIDs.")")
            
        );
        $allInfosNeeded = $MContests->searchQuery($from, $where, array("*"), false, false, $join,"GROUP BY userid");
        $usersAndContests = $MContests->getRowsAssoc($allInfosNeeded);       
        foreach($usersAndContests as $key => $value){
            $umail->send_userValidationEnded($value['user_email'],$value['user_login'],$value['title']);
        }
    }
    
    public function sendMailsEndOfVideoValidation($contestid){
        $MContests = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $umail = USingleton_vidwiz::getInstances("UMails_vidwiz");
        global $config;
        $from = array(
            $config['tables']['partecipations'],
            $config['tables']['users'],
            $config['tables']['contests']
            );
        $join = array(
            array($config['tables']['partecipations'].".userid",$config['tables']['users'].".ID"),
            array($config['tables']['partecipations'].".contestid",$config['tables']['contests'].".id")
        );
        $where = array(
            array($config['tables']['partecipations'].".contestid"," = ",$contestid)
            
        );
        $allInfosNeeded = $MContests->searchQuery($from, $where, array("*"), false, false, $join,"GROUP BY videoid");
        $usersAndContests = $MContests->getRowsAssoc($allInfosNeeded);
        foreach($usersAndContests as $key => $value){
            
            $umail->send_videoValidationEnded($value['user_email'],$value['user_login'],$value['title']);
        }
    }


    public function fixCharts($charts){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        
        foreach($charts as $key => $value){
            if($value['score'] != "0"){
                $k  = round((int)$value["scoreNr"]/10);
                $m1 = $value['score'];
                $n  = (int)$value["scoreNr"];
                $b  = 5*$k;
                $m2 = (($m1*(pow($n,2)+$n*$k) + $b*($n+$k))/(pow($n,2) + 2*$n*$k + pow($k,2)));
                $charts[$key]["score"] = $m2;
            }
            else{
                $charts[$key]["score"] = "0";
            }
        }
        uasort($charts, array($this, 'sortArrayCharts'));
        
        return $charts;
    }

    public function getContests($justForUser = false){
        $model = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        global $config;     global $current_user;
        
        $date = date("Y-m-d")." 00:00:00";
        $where = array(
            array('status','<>','closed'),
            array('startDate',"<=",$date)
        );
        $query = $model->searchQuery($config['tables']['contests'], $where, array("*"));
        
        if($justForUser == true){
            get_currentuserinfo();
            $userid = $current_user->ID;
            $where = array(
                array('userid','=',$userid)
            );
            $query2 = $model->searchQuery($config['tables']['partecipations'],$where,array("contestid"));
            $query = $query."AND id NOT IN (".$query2.")";}
        $results = $model->getRowsAssoc($query);
        if(count($results) != 0)
            return $results;
        return false;
    }
    
    public function getContestsSubscription(){
        $model = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        global $config;     global $current_user;
        
        $date = date("Y-m-d")." 00:00:00";
        $where = array(
            array('status','=','subscription'),
        );
        $query = $model->searchQuery($config['tables']['contests'], $where, array("*"));        
        get_currentuserinfo();
        $userid = $current_user->ID;
        $where = array(
            array('userid','=',$userid)
        );
        $query2 = $model->searchQuery($config['tables']['partecipations'],$where,array("contestid"));
        $query = $query."AND id NOT IN (".$query2.")";
        $results = $model->getRowsAssoc($query);
        if(count($results) != 0)
            return $results;
        return false;
    }
    
    public function getContestsVoting(){
        $model = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        global $config;
        $where = array(
          array("status","=","voting"),
          array("winnerSelection","=","1")
        );
        $query = $model->searchQuery($config['tables']['contests'],$where,array("*")," 0,5 ","id DESC");
        $results = $model->getRowsAssoc($query);
        $debug->debugLog($results);
        return $results;
    }
    
    public function userAlreadyInContest($id,$contestid){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $model = USingleton_vidwiz::getInstances("MContests_vidwiz");
        global $config;
        $query = $model->searchQuery($config['tables']['partecipations'], array(array("userid","=",$id),array("contestid","=",$contestid)));
        
        $count = $model->getRows($query);
        
        $count = count($count);
        
        if($count==0) return false; else return true;
    }
    
    public function addUserInContest($contid,$userid,$contestType){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $model = USingleton_vidwiz::getInstances("MPartecipations_vidwiz");
        $entity = USingleton_vidwiz::getInstances("EPartecipations_vidwiz");
        $fields = array(
            "userid"    => $userid,
            "contestid" => $contid,
            "videoid"   => "0"
        );
        if($contestType == "open")
            $fields["user_approved"] = "1";
        $object = $entity->generateObject($fields);
        $query = $model->insertQuery($object);
        $model->executeQuery($query);
        
    }
    
    public function updateUserInContest($contid,$userid,$disapproved = false){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $model = USingleton_vidwiz::getInstances("MPartecipations_vidwiz");
        global $config;
        $where = array(
            array("userid","=",$userid),
            array("contestid","=",$contid)
        );
        if($disapproved == false)
            $valueSet = array(
                array("user_approved","1")
            );
        else
            $valueSet = array(
                array("user_approved","-1")
            );
        $query = $model->updateQuery($config['tables']['partecipations'], $valueSet, $where);
        $model->executeQuery($query);
        
    }

    public function getContestInfos($id){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $model = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $CVideos = USingleton_vidwiz::getInstances("CVideos_vidwiz");
        global $config;
        $query = $model->searchQuery($config['tables']['contests'], array(array('id','=',$id)));
        $baseInfos = $model->getRowsAssoc($query);
        if($baseInfos[0]['status'] != "voting")
            $query = $model->searchQuery(array($config['tables']['partecipations'],"wp_users"), array(array("contestid","=",$id),array("user_approved","=","0")), array("*"), false, false, array(array("wp_users.ID",$config['tables']['partecipations'].".userid")));
        else{
            $query = $model->searchQuery(array($config['tables']['partecipations'],"wp_users"), array(array("contestid","=",$id),array("user_approved","=","1"),array("video_approved","=","1"),array("placing","=","0")), array("*"), false, false, array(array("wp_users.ID",$config['tables']['partecipations'].".userid")));
            
            }
        $users = $model->getRowsAssoc($query);
        $charts = array_reverse($this->makeCharts($baseInfos[0]['id'], true));
        $query = $model->searchQuery(array($config['tables']['partecipations'],$config['tables']['videos']), array(array("contestid","=",$id),array("video_approved","=","0"),array("converted","=","1")), array("*"), false, false, array(array($config['tables']['videos'].".id",$config['tables']['partecipations'].".videoid")));
        $videos = $model->getRowsAssoc($query);
        foreach ($videos as $key => $value){
            $videos[$key] = $CVideos->absPathInArray($value,array('file_position','thumb'));
            }
        $where = array(
            array("contestid","=",$baseInfos[0]['id']),
            array("video_approved","=","1"),
            array("user_approved","=","1"),
            array("placing","<>","0")
        );
        $lastInCharts = $model->searchQuery($config['tables']['partecipations'], $where,array("placing"), "1","placing ASC");
        $lastInCharts  = $model->getRowsAssoc($lastInCharts);
        if(count($lastInCharts) == "0"){
            $where = array(
                array("contestid","=",$baseInfos[0]['id']),
                array("video_approved","=","1"),
                array("user_approved","=","1")
            );
            $lastInCharts = $model->countEntries($config['tables']['partecipations'], $where);
            }
        else
            $lastInCharts = $lastInCharts[0]['placing'];
        
        $results['baseInfos'] = $baseInfos;
        $results['users']     = $users;
        $results['videos']    = $videos;
        //ultima posizione occupata della classifica
        $results['lastInCharts'] = $lastInCharts;
        $results['charts'] = $charts;
        return $results;
    }
    
    public function setVideoId($vidid,$contestid){
        $model = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        global $config;
        global $current_user;
        get_currentuserinfo();
        $userid = $current_user->ID;
        $date = date("Y-m-d")." 00:00:00";
        $valueSet = array (
            array("videoid",$vidid)
        );
        $where = array (
            array("contestid","=",$contestid),
            array("userid","=",$userid),
            array("user_approved","=","1"),
            array("videoid","=","0")
        );
        $query = $model->updateQuery($config['tables']['partecipations'], $valueSet, $where);
        $model->executeQuery($query);
    }

    public function getSubscrivedContestsNoVideoUploaded(){
        $VContests = USingleton_vidwiz::getInstances("VContests_vidwiz");
        $MContests = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $model = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $check = USingleton_vidwiz::getInstances("UChecks_vidwiz");
        global $config;     global $current_user;

        $where = array(
            array('status','=','video_validation'),
        );
        $query = $model->searchQuery($config['tables']['contests'], $where, array("*"));
        get_currentuserinfo();
        $userid = $current_user->ID;
        $where = array(
            array('userid','=',$userid),
            array('user_approved','=','1'),
            array('videoid','=','0')
        );
        $query2 = $model->searchQuery($config['tables']['partecipations'],$where,array("contestid"));
        $query = $query."AND id IN (".$query2.")";
        $results = $model->getRowsAssoc($query);
        
        foreach($results as $key => $value){
            if(!$check->check_canUploadVideoInContest($value['id']))
                unset($results[$key]);
        }
        if(count($results) != 0)
            return $results;
        return false;
    }
    
    public function enableContestPageAccess($id){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $MContests = USingleton_vidwiz::getInstances("MContests_vidwiz");
        global $config;
        $where = array(
            array("id","=",$id)
        );
        $query = $MContests->searchQuery($config['tables']["contests"],$where,array("page_id"));
        $debug->debugLog($query);
        $results = $MContests->getRowsAssoc($query);
        $pageid = $results[0]['page_id'];
        $post['ID'] = $pageid;
        $post['post_status'] = 'publish';
        wp_update_post($post);
        
    }
    
    public function vidwiz_contests_info(){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $view = USingleton_vidwiz::getInstances("VContests_vidwiz");        
        $id = $view->getRequest('id');
        if($id == false) return false;
        $info = $this->getContestInfos($id);
        //video catturati correttamente, provare con + video e + utenti
        $return = $view->getContestsInfoView($info,$id);
        return $return;
        
    }
    
    public function vidwiz_contests_page(){
        $VContests = USingleton_vidwiz::getInstances("VContests_vidwiz");
        $MContests = USingleton_vidwiz::getInstances("MContests_vidwiz");
        if(current_user_can("administrator"))
            $view = "administrator";
        if(current_user_can("author"))
            $view = "author";
        if(!isset($view)) die();
        return $VContests->getContestsPage($view);
    }
    
    public function vidwiz_getActiveContests(){
        $VContests = USingleton_vidwiz::getInstances("VContests_vidwiz");
        $MContests = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $activeContests = $this->getContests();
        $debug=USingleton_vidwiz::getInstances("UDebug_vidwiz");
        
        if($activeContests != false)
            foreach($activeContests as $key => $value){
                $activeContests[$key]['startDate'] = $MContests->dateToEng($value['startDate']);
                $activeContests[$key]['stopDate'] = $MContests->dateToEng($value['stopDate']);
            }
        $return = $VContests->getActiveContests($activeContests);
        return $return;
    }
     
    public function  vidwiz_contests_subscription(){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $view = USingleton_vidwiz::getInstances("VContests_vidwiz");
        $check = USingleton_vidwiz::getInstances("UChecks_vidwiz");
        $model = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $id = $view->getRequest("id");
        $contest = $model->getContestFromId($id);
        $contestType = $contest['contestType'];
        global $current_user;
        get_currentuserinfo();
        $userid = $current_user->ID;
        if(current_user_can('author') || current_user_can('administrator')){
            $var[] = $this->userAlreadyInContest($userid,$id);
            $var[] = $check->check_contestStatus($id,"subscription");
            
            if(!$this->userAlreadyInContest($userid,$id) && $check->check_contestStatus($id,"subscription") == true){
                $this->addUserInContest($id,$userid,$contestType);
                return "success";
            }
        }
        else return "0";
    }
    
    public function vidwiz_allow_disallowUserInContest(){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $view = USingleton_vidwiz::getInstances("VContests_vidwiz");
        $umail = USingleton_vidwiz::getInstances("UMails_vidwiz");
        $model = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $userid = $view->getRequest("userid");
        $contestid = $view->getRequest('contestid');
        $contestname = $model->getContestFromId($contestid);
        $contestname = $contestname['title'];
        $allowdisallow = $view->getRequest('allowdisallow');
        $return = "";
        $userdata = $model->getUserDataFromId($userid);
        if($allowdisallow == "allow"){
            if($this->userAlreadyInContest($userid,$contestid)){
                $this->updateUserInContest($contestid,$userid);
                $umail->send_allowedUserInContest($userdata->user_email,$userdata->user_login,$contestname);
                $return = "success";
            }
        }
        else {
            if($this->userAlreadyInContest($userid,$contestid)){
                $this->updateUserInContest($contestid,$userid,true);
                $umail->send_NOTallowedUserInContest($userdata->user_email,$userdata->user_login,$contestname);
                $return = "success";
            }
        }
        return $return;
    }
    
    public function vidwiz_allow_disallowVideoInContest(){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $view = USingleton_vidwiz::getInstances("VContests_vidwiz");
        $model = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $umail = USingleton_vidwiz::getInstances("UMails_vidwiz");
        $allowdisallow = $view->getRequest('allowdisallow');
        $username = $view->getRequest("username");
        $userid = $model->getIdFromUsername($username);
        $contestid = $view->getRequest('contestid');
        $videoid = $view->getRequest("videoid");
        $contestname = $model->getContestFromId($contestid);
        $contestname = $contestname['title'];
        $userdata = $model->getUserDataFromId($userid);
        
        $return = "";
        if($allowdisallow == "allow"){
            $model->allowVideoInContest($userid,$contestid,$allowdisallow);
            $umail->send_allowedVideoInContest($userdata->user_email,$userdata->user_login,$contestname);
            $return = "success";
        }
        if($allowdisallow == "disallow"){
            $model->allowVideoInContest($userid,$contestid,$allowdisallow);
            $umail->send_NOTallowedVideoInContest($userdata->user_email,$userdata->user_login,$contestname);
            $return = "success";
        }
        return $return;
    }
    
    public function vidwiz_getVideoInfosContestVoting(){
        $view = USingleton_vidwiz::getInstances("VContests_vidwiz");
        $model = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        global $config;
        $userid = $view->getRequest("userid");
        $contestid = $view->getRequest("contestid");
        if($userid == false || $contestid == false)
            die();
        $where = array(
            array("contestid","=",$contestid),
            array("userid","=",$userid),
            array("video_approved","=","1"),
            array("user_approved","=","1"),
        );
        $select = array("videoid");
        $userVideoForContest = $model->searchQuery($config['tables']['partecipations'], $where, $select);
        $where = array(
            array("id"," IN ","(".$userVideoForContest.")")
        );
        $query = $model->searchQuery($config['tables']['videos'], $where);
        $results  = $model->getRowsAssoc($query);
        $results[0] = $this->absPathInArray($results[0],array('file_position','thumb'));
        $output = "|beg|";
        foreach($results[0] as $key=>$value){
            $output .= $key."|x|".$value."|xxx|";
        }
        $palinsesto = $video_palinsesto['palinsesto'];
        $output .= "|end|";
        
        return $output;
    }
    
    public function vidwiz_deleteUserFromCharts(){
        $view = USingleton_vidwiz::getInstances("VContests_vidwiz");
        $model = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        global $config;
        
        $userid = $view->getRequest("userid");
        $contestid = $view->getRequest("contestid");
        if($userid == false || $contestid == false)
            die();
        
        $where = array(
            array("contestid","=",$contestid),
            array("userid","=",$userid),
            array("video_approved","=","1"),
            array("user_approved","=","1"),
            array("placing","=","0")
        );
        $where = array(
            array("contestid","=",$contestid),
            array("video_approved","=","1"),
            array("user_approved","=","1"),
            array("placing","<>","0")
        );
        
        $lastInCharts = $model->searchQuery($config['tables']['partecipations'], $where,array("placing"), "1","placing ASC");
        $lastInCharts  = $model->getRowsAssoc($lastInCharts);
        if(count($lastInCharts) == 0)
            $lastInCharts = "0";
        $actualPosition;
        if($lastInCharts == "0"){
            $where = array(
                array("contestid","=",$contestid),
                array("video_approved","=","1"),
                array("user_approved","=","1")
            );
            $nrInContest = $model->countEntries($config['tables']['partecipations'], $where);
            $actualPosition = $nrInContest;  
            }
        else
            $actualPosition = $lastInCharts[0]['placing']-1;
        $valueSet = array(
            array("placing",$actualPosition)
        );
        
        $where = array(
            array("contestid","=",$contestid),
            array("userid","=",$userid),
            array("video_approved","=","1"),
            array("user_approved","=","1"),
            array("placing","=","0")
        );
        $update = $model->updateQuery($config['tables']['partecipations'], $valueSet, $where);
        $model->executeQuery($update);
        if((string)$actualPosition == "2"){
            $where = array(
                array("contestid","=",$contestid),
                array("video_approved","=","1"),
                array("user_approved","=","1"),
                array("placing","=","0")
            );
           $valueSet = array(
            array("placing","1")
            );
            $update = $model->updateQuery($config['tables']['partecipations'], $valueSet, $where);
            $model->executeQuery($update);
            $this->closeContests();
            
            }
        return "|beg|".(string)$actualPosition."|end|";
    }
    
    public function vidwiz_submitScore(){
        $model = USingleton_vidwiz::getInstances("MScores_vidwiz");
        $view = USingleton_vidwiz::getInstances("VContests_vidwiz");
        $check = USingleton_vidwiz::getInstances("UChecks_vidwiz");
        $wordpress = USingleton_vidwiz::getInstances("UWordpress_vidwiz");
        $MContests = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        
        global $config;
        $videoid = $view->getRequest("videoid");
        $score = $view->getRequest("score");
        $errors[] = $check->check_videoInContest($videoid,"voting");
        $errors[] = $check->check_score($score);
        $errors[] = is_user_logged_in();
        $userid = $wordpress->getUserData();
        $userid = $userid->ID;
        $where = array(array("userid","=",$userid),array("videoid","=",$videoid));
        $contestid = $MContests->getContestIdFromVideoInContest($videoid);
        $count = $model->countEntries($config['tables']['scores'], $where);
        if(!in_array(false, $errors) && (int)$count == 0){
            $model->submitScore($score,$videoid,$userid,$contestid);
            }
        else die();
    }
    
    public function vidwiz_getContestsToUpload(){
        $view = USingleton_vidwiz::getInstances("VContests_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $subscribedContestsNoVideo = $this->getSubscrivedContestsNoVideoUploaded();
        $return = $view->getSubscribedContestsNoVideoView($subscribedContestsNoVideo);
        return $return;
    }
}
?>
